package shuai.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import shuai.model.User;

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	public void addUser(User user) {
		getHibernateTemplate().save(user);

	}

	public void delUser(int userNo) {
		getHibernateTemplate().delete(this.get(userNo));

	}

	public void updateUser(User user) {
		getHibernateTemplate().update(user);

	}

	public User get(int userNo) {
		return getHibernateTemplate().get(User.class, userNo);
	}

	public List<User> searchUser(final User user) {
		List<User> list = getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				Criteria criteria = session.createCriteria(User.class);
				if (criteria != null) {
					if (user.getUsername()!=null && !user.getUsername().equals("")) {
						criteria.add(Restrictions.like("username", user.getUsername(), MatchMode.ANYWHERE));
					}
				}
				return criteria.list();
			}
		});
		return list;
	}

	public List<User> searchUser(String hql) {
		return getHibernateTemplate().find(hql);
	}

}
